import { ComponentClass } from 'react'
import { connect } from '@tarojs/redux'
import Taro, { Component, Config } from '@tarojs/taro'
import { View, Input, Image } from '@tarojs/components'
import { SDBody, SDLoading } from 'sudao-ui'
import SDUtils from 'sudao-utils'

import PageProps from '../../../redux'
import { login, logout } from '../../../redux/actions'

import GoodsItem from '../../../comps/goods-item'
import SKUPicker from '../../../comps/sku-picker'

import EmptyIcon from '../../../images/ic_nothing_search.png'
import NextIcon from '../../../images/ic_next.png'

import './index.less'

type PageState = {
  keywords: string,
  mainIsLoading: boolean,
  dataList: any[],                        // 商品数据列表
  loading: boolean,                       // 是否正在加载中
  hasData: boolean,                       // 是否有商品数据
  hasMore: boolean,                       // 是否有更多数据
  hideLoading: boolean,                   // 强制隐藏loading
}

type PageOwnProps = {}

interface GoodsSearchResultPage {
  props: PageProps & PageOwnProps
}

@connect(({userState}) => ({
  userState
}), (dispatch) => ({
  login(userInfo) {
    dispatch(login(userInfo))
  },
  logout() {
    dispatch(logout())
  }
}))
class GoodsSearchResultPage extends Component<PageOwnProps, PageState> {

  constructor () {
    super()
    this.state = {
      mainIsLoading: true,
      keywords: '',
      dataList: [],
      loading: false,
      hasData: true,
      hasMore: true,
      hideLoading: false
    }
  }

  config: Config = {
    navigationBarTitleText: '搜索结果',
    enablePullDownRefresh: true
  }

  keywords: string = ''

  componentDidMount () {
    this.keywords = (this.$router.params || {}).keywords || 'B'
    this.setState({
      keywords: this.keywords
    })
    this.fetchData(0, true)
  }

  onPullDownRefresh () {
    this.fetchData(0)
  }

  onReachBottom () {
    const { dataList } = this.state
    this.fetchData(dataList.length)
  }

  render () {
    const { keywords, mainIsLoading, dataList, hasData, hasMore, hideLoading, loading } = this.state
    return (
      <SDBody sd-class='container' loading={mainIsLoading}>
        <View>
          <View className="search-content border-bottom_1px">
            <View className="search-outer">
              <Input className="search-input" value={keywords} confirmType='search' placeholder='请输入关键字' onInput={this.onInputValueChange} onConfirm={this.onSearch} />
            </View>
          </View>
          <View style='height: 128rpx'></View>
        </View>
        {

          dataList.length > 0 ? (
            <View className="cell-list-pic">
              {
                dataList.map((item, index) => {
                  return (
                    <View className="cell-arrange-pic" key={index}>
                      <GoodsItem
                        extData={index}
                        width={336}
                        height={550}
                        imgUrl={item.coverImage || ''}
                        title={item.name}
                        price={SDUtils.formatPrice(`${item.minPrice}`)}
                        showTagPrice={true}
                        tagPrice={SDUtils.formatPrice(`${item.minTagPrice}`)}
                        showCartNum={false}
                        cartNum={0}
                        showSalesVolume={true}
                        salesVolume={item.salesVolume || 0}
                        showCartIcon={true}
                        bgColor='#fff'
                        onClick={this.gotoGoodsDetail}
                        onCartClick={this.onCartIconTaped}
                      />
                    </View>
                  )
                })
              }
            </View>
          ) : null
        }
        <SDLoading loading={loading} hasData={hasData} hasMore={hasMore} hideLoading={hideLoading}>
          <View className="main-empty">
            <View className="header">
              <Image className="icon" src={EmptyIcon}></Image>
              <View className="title">抱歉，没有搜索到相关商品</View>
            </View>
            <View className="content">
              <View className="section-header">
                <View className="title">推荐商品</View>
                <View className="right" onClick={this.onMoreBtnTaped}>
                  <View className="item">
                    <View className="item-title">更多</View>
                    <View className="item-icon-content">
                      <Image className="ic-next" src={NextIcon}></Image>
                    </View>
                  </View>
                </View>
              </View>
              <View className="empty-list">
                {
                  Array.from({length: 20}, (_, v) => v).map((_, index) => {
                    return (
                      <View className="empty-cell" key={index}>
                        <GoodsItem
                          width={336}
                          height={548}
                          imgUrl=''
                          title='银河系心形链接扣925银手镯'
                          price='¥ 90.00'
                          showTagPrice={true}
                          tagPrice='¥12000.00'
                          showCartNum={false}
                          showSalesVolume={true}
                          salesVolume='998'
                          bgColor='#fff'
                          type='recommend'
                          onClick={this.gotoGoodsDetail}
                          onCartClick={this.onCartIconTaped}
                        />
                      </View>
                    )
                  })
                }
              </View>
            </View>
          </View>
        </SDLoading>
        <SKUPicker ref='compsSkuPicker' onSelect={this.onSkuSelect}/>
      </SDBody>
    )
  }

  onInputValueChange = e => {
    this.keywords = e.detail.value
  }

  onSearch = () => {
    this.fetchData(0, true)
  }

  fetchData = async (offset: number = 0, resetData: boolean = false) => {
    const limit = 20
    let keywords = this.keywords
    let { loading, hasData, hasMore, dataList } = this.state
    if (loading || (offset > 0 && !hasMore)) { return }
    if (offset == 0) {
      dataList = []
    }
    let pageState: any = {
      loading: true,
      hasMore: true,
      hasData: true,
      hideLoading: resetData
    }
    if (resetData) {
      pageState.dataList = dataList
    }

    await this.setState({...pageState})

    try {
      const resp = await SDUtils.doGet('/wxmini/traderProduct', {
        offset: offset,
        limit: limit,
        keywords: keywords,
        traderId: '1'
      })
      dataList = dataList.concat(resp.items ||[])
      hasData = resp.total > 0
      hasMore = resp.total > dataList.length
    } catch (e) {
      SDUtils.showMsg(e)
    } finally {
      Taro.stopPullDownRefresh()
      this.setState({
        mainIsLoading: false,
        loading: loading,
        hasMore: hasMore,
        hasData: hasData,
        dataList: dataList
      })
    }

  }

  onSkuSelect = () => {
    this.refs.compsSkuPicker && this.refs.compsSkuPicker.dismiss()
  }

  onMoreBtnTaped = () => {
    SDUtils.jumpTo('/pages/goods/list/index', {comeFrom: 'recommend'})
  }

  onCartIconTaped = (index: number, e) => {
    e.stopPropagation && e.stopPropagation()
    const { dataList } = this.state
    let productId = dataList[index].productId
    if (!productId) {
      SDUtils.showMsg('商品ID错误')
      return
    }
    this.refs.compsSkuPicker && this.refs.compsSkuPicker.show(productId)
  }

  gotoGoodsDetail = (index: number) => {
    const { dataList } = this.state
    let productId = dataList[index].productId
    if (!productId) {
      SDUtils.showMsg('商品ID错误')
      return
    }
    SDUtils.jumpTo('/pages/goods/detail/index', { productId: productId})
  }
}

export default GoodsSearchResultPage as ComponentClass<PageOwnProps, PageState>
